package com.cms.filter;

import java.io.File;
import java.io.IOException;  
import java.util.List;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; 
import com.cms.common.CmsContext;
import com.cms.common.StringUtils;
import com.cms.constant.CmsConstant;
import com.cms.model.TrAdminUser;
import com.google.common.collect.Lists;

public class AuthVerificationFilter implements Filter{

	private List<String>excludeurls= Lists.newArrayList("/index.do","/login.do","/jcaptcha");
	
	@Override
	public void destroy() {
		excludeurls.clear();
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain) throws ServletException, IOException 
	{ 
		HttpServletRequest request =(HttpServletRequest)req;
	    HttpServletResponse response =(HttpServletResponse)resp;
		HttpSession session = request.getSession();
		StringBuilder sb = new StringBuilder();
		sb.append(request.getContextPath()).append("/index.do");
		TrAdminUser tu=(TrAdminUser) session.getAttribute(CmsConstant.CURRENT_USER);
		String uri = request.getRequestURI();
		String actString=request.getParameter(CmsConstant.ACTIVITY_CODE);
		if(!StringUtils.isBlank(actString))
		{
			 CmsContext.setActivityCode(actString);
		}
		if(tu!=null)//当前用户已登录
		{
			if(StringUtils.equals(uri, request.getContextPath()+"/")
			  ||StringUtils.equals(uri, "/cms/main.do"))
			{
				request.getRequestDispatcher("/main.do").forward(request, response);
				return;
			}
			/*
			String referer = request.getHeader("Referer");
			if(referer==null||!referer.contains(AppPropertiesUtil.getStringValue(CmsConstant.CMS_REFERER_ADDRESS)))
			{
				response.setContentType("text/plain;charset=UTF-8");
				PrintWriter out= response.getWriter();
			    out.print("<script>alert('非法路径访问，服务器拒绝响应。');location.href='"+sb.toString()+"';</script>");	
			    out.flush();
				return;
			}*/
			filterChain.doFilter(req, resp);
			return;
		}
		
		if(this.verificationUrl(uri,request))
		{
			filterChain.doFilter(req, resp);
		}
		else
		{
			response.sendRedirect(sb.toString());
		}
		
	}

	/**
	 * 
	 * @param uri
	 * @return
	 */
	private boolean verificationUrl(String uri,HttpServletRequest req)
	{ 
	    if(StringUtils.isBlank(uri))
	    {
	    	return false;
	    }
	    if(StringUtils.equals(uri, req.getContextPath()+File.separator))
	    {
	        return true;	
	    }
	    for(String excludeurl:excludeurls)
	    {
	    	if(uri.contains(excludeurl))
	    	{
	    		return true;
	    	}
	    }
	    return false;
	}
	
	
	@Override
	public void init(FilterConfig config) throws ServletException {
	}

}
